from typing import List
import logging
from fastapi import APIRouter, HTTPException, Path, Query
from app.schemas.warehouse_schemas import (
    WarehouseCreate, 
    WarehouseUpdate, 
    WarehouseResponse
)
from app.services.warehouse_service import WarehouseService

logger = logging.getLogger(__name__)
router = APIRouter()

@router.post("/", response_model=WarehouseResponse, status_code=201)
async def create_warehouse(warehouse: WarehouseCreate):
    """创建新仓库"""
    try:
        logger.info(f"接收创建仓库请求: {warehouse.model_dump()}")
        result = await WarehouseService.create_warehouse(warehouse)
        logger.info(f"仓库创建成功: warehouse_id={result.id}")
        return result
    except ValueError as e:
        logger.error(f"创建仓库失败(仓库已存在): {str(e)}")
        raise HTTPException(status_code=409, detail=str(e))
    except Exception as e:
        logger.error(f"创建仓库失败(未知错误): {str(e)}", exc_info=True)
        raise HTTPException(status_code=400, detail=f"创建仓库失败: {str(e)}")

@router.get("/{warehouse_id}", response_model=WarehouseResponse)
async def get_warehouse(warehouse_id: int = Path(..., title="仓库ID", gt=0)):
    """获取单个仓库信息"""
    try:
        logger.info(f"获取仓库信息: warehouse_id={warehouse_id}")
        warehouse = await WarehouseService.get_warehouse(warehouse_id)
        if not warehouse:
            logger.warning(f"仓库不存在: warehouse_id={warehouse_id}")
            raise HTTPException(status_code=404, detail="Warehouse not found")
        logger.debug(f"成功获取仓库信息: warehouse_id={warehouse_id}")
        return warehouse
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取仓库信息失败: {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail="Internal server error")

@router.get("/", response_model=List[WarehouseResponse])
async def list_warehouses(
    skip: int = Query(0, ge=0, description="跳过的记录数"),
    limit: int = Query(10, ge=1, le=100, description="返回的记录数"),
    name: str | None = Query(None, description="仓库名称（支持模糊查询）"),
    address: str | None = Query(None, description="仓库地址（支持模糊查询）")
):
    """获取仓库列表"""
    try:
        logger.info(
            f"获取仓库列表: skip={skip}, limit={limit}, "
            f"name={name}, address={address}"
        )
        warehouses = await WarehouseService.list_warehouses(
            skip=skip, limit=limit, name=name, address=address
        )
        logger.debug(f"成功获取仓库列表: count={len(warehouses)}")
        return warehouses
    except Exception as e:
        logger.error(f"获取仓库列表失败: {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail="Internal server error")

@router.put("/{warehouse_id}", response_model=WarehouseResponse)
async def update_warehouse(
    warehouse_id: int = Path(..., title="仓库ID", gt=0),
    warehouse: WarehouseUpdate = None
):
    """更新仓库信息"""
    try:
        logger.info(
            f"更新仓库信息: warehouse_id={warehouse_id}, "
            f"update_data={warehouse.model_dump() if warehouse else None}"
        )
        
        if not warehouse:
            logger.error("更新数据为空")
            raise HTTPException(status_code=400, detail="Update data is required")
            
        updated_warehouse = await WarehouseService.update_warehouse(
            warehouse_id, warehouse
        )
        
        if not updated_warehouse:
            logger.warning(f"仓库不存在: warehouse_id={warehouse_id}")
            raise HTTPException(status_code=404, detail="Warehouse not found")
            
        logger.info(f"仓库更新成功: warehouse_id={warehouse_id}")
        return updated_warehouse
        
    except ValueError as e:
        logger.error(f"更新仓库失败(数据验证): {str(e)}")
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        logger.error(f"更新仓库失败(未知错误): {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail="Internal server error")
    
    